package com.example.travel.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.travel.mapper.NoteMapper;
import com.example.travel.pojo.frontend.FNote;
import com.example.travel.pojo.orm.Note;
import com.example.travel.util.FileSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class NoteService {

    @Autowired
    private NoteMapper mapper;

    @Value("${web.upload-path}")
    private  String uploadPath;

    private String serverPrefix;

    public void setServerPrefix(String serverPrefix) {
        this.serverPrefix = serverPrefix;
    }

    public List<Note> getAllNotes(){
        return mapper.getAllNotes();
    }

    public Note getNoteByNoteId(int noteId){
        return mapper.getNoteByNoteId(noteId);
    }

    public List<Note> getNoteByUserId(int userId){
        return mapper.getNoteByUserId(userId);
    }

    public int addNote(Note note){
        return mapper.addNote(note);
    }

    public int updateNote(Note note){
        return mapper.updateNote(note);
    }

    public int deleteNote(int noteId){
        return mapper.deleteNote(noteId);
    }

    public boolean notePack(FNote fNote,String serverPrefix) throws IOException {
        this.serverPrefix = serverPrefix;
        FileSave.serverPrefix = this.serverPrefix;
        MultipartFile file = fNote.getImage();
        System.out.println(uploadPath);
        String imageUrl = FileSave.saveMultipartFile(file,uploadPath);
        String info = fNote.getUploadInfo();
        System.out.println(info);
        JSONObject jsonObject = JSON.parseObject(info);
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        int userId = jsonObject.getInteger("userId");

        Note note = new Note(1,userId,title,content,imageUrl);
        int i = mapper.addNote(note);
        if (i==1){
            System.out.println("插入游记成功");
            return true;
        }else {
            System.out.println("插入游记失败");
            return false;
        }

    }


}
